#include <iostream>
#include <fstream>

namespace NIPSCompetition {

    template<typename T>
    void saveBin(const char *filename, T *array, unsigned int n_data, unsigned int dim) {
        std::ofstream out(filename, std::ios::binary | std::ios::out);
        out.write((char *) &n_data, sizeof(unsigned int));
        out.write((char *) &dim, sizeof(unsigned int));
        out.write((char *) array, n_data * dim * sizeof(T));
        out.close();
    }

    template<typename T>
    T *loadBin(const char *filename, unsigned int &n_data, unsigned int &dim, unsigned int read_length = -1) {
        std::ifstream in(filename, std::ios::binary);
        if (!in.is_open()) {
            std::cerr << "Open file error" << std::endl;
            exit(-1);
        }

        in.read((char *) &n_data, 4);
        in.read((char *) &dim, 4);

        if (read_length == -1) {
            read_length = n_data;
        }
        T *data = new T[(size_t) read_length * (size_t) dim];

        in.read((char *) (data), dim * sizeof(T) * read_length);

        in.close();

        return data;
    }
}